package com.azure.bigstore.fileUpload;

import java.io.File;
import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by liuhuaibin on 2018/1/24.
 */
@RestController
public class UploadController {

    @Autowired
    private UploadService uploadService;

    /**
     * 文件上传根目录
     * D:/static/
     */
    /*@Value("${file.location}")
    private String webUploadPath;*/

    @PostMapping(value = "/fileUpload")
    public String fileUpload(@RequestParam("file") MultipartFile file,HttpServletRequest request) {

        if (!file.isEmpty()) {
            if (true) {
                try {
                    /*
                    // 获取图片的文件名
                    String fileName = file.getOriginalFilename();
                    // 获取图片的扩展名
                    String extensionName = StringUtils.substringAfter(fileName, ".");
                    // 新的图片文件名 = 获取时间戳+"."图片扩展名    12312153161234.jpg
                    String newFileName = String.valueOf(System.currentTimeMillis()) + "." + extensionName;
                    System.out.println("newFileName:"+newFileName);

                    //temp: upload/images/
                    String temp = "upload" + File.separator + "images" + File.separator;
                    //文件路径filePath:    D:/static/upload/images/
                    String filePath = webUploadPath.concat(temp);

                    //dest:   D:/static/upload/images/12312153161234.jpg
                    File dest = new File(filePath, newFileName);
                    if (!dest.getParentFile().exists()) {
                        dest.getParentFile().mkdirs();
                    }
                    // 上传到指定目录
                    file.transferTo(dest);

                    // 将反斜杠转换为正斜杠
                    String data = temp.replaceAll("\\\\", "/") + newFileName;
                    String realURL = request.getScheme().toLowerCase()+"://"+request.getServerName()+":"+request.getServerPort()+"/";

                    return "上传成功:"+realURL+data;
                    */
                    return uploadService.upload(file,request);

                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("=========上传失败！");
                    return "bad";
                }
            }
        }
        return "none";
    }

}
